package com.abc.robot01.vivemodel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.Condition2
import com.abc.robot01.retrofit.bean.Condition3
import com.abc.robot01.retrofit.bean.FetchDataRequest9
import com.abc.robot01.retrofit.bean.HouseType
import com.abc.robot01.retrofit.bean.Item8
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.json.JSONObject


class HouseLayoutViewModel : ViewModel() {
    val TAG = "HouseLayoutViewModel"

    val showLeft =  mutableStateOf(true)
    val loading =  mutableStateOf(false)
    val showRight =  mutableStateOf(false)

    val expanded1 =  mutableStateOf(false)
    val expanded2 =  mutableStateOf(false)
    val expanded3 =  mutableStateOf(true)

    val selected10 =  mutableStateOf("全部")
    val selected20 =  mutableStateOf("全部")
    val selected30 =  mutableStateOf("全部")

    // MutableStateFlow 用来保存当前的列表状态
    private val _questionList = MutableStateFlow<List<Item8>>(emptyList())
    val questionList: StateFlow<List<Item8>> = _questionList
    val name = mutableStateOf("")

    //当前已经输入的手机号码
    val phone = mutableStateOf("")
    val shequ = mutableStateOf("")
    val designPackageId = mutableStateOf("")


    val show =  mutableStateOf(true)





    //当前选择的户型
    val selectedHouseType = mutableStateOf("")

    var selectedIndex = mutableStateOf(-1)

    fun reset(){
        selectedHouseType.value = ""
        name.value = ""
        selectedIndex.value = -1 ;
        selected1.value = false
        selected2.value = false
        selected10.value = "全部"
        selected20.value = "全部"
        selected30.value = "全部"
        expanded1.value = false
        expanded2.value = false
//        expanded3.value = false
        selectedDesigner.value=""
        selectedRegion.value=""
    }

    //当前选择的创建者
    val selectedDesigner = mutableStateOf("")

    //当前选择的社区地区
    val selectedRegion = mutableStateOf("")


    val selected1 =  mutableStateOf(false)
    val selected2 =  mutableStateOf(false)
    var housePlansId=""
    var thumbnail=""
    // MutableStateFlow 用来保存当前的列表状态
    private val _houseTypeList = MutableStateFlow<List<HouseType>>(mutableListOf(HouseType()))
    val houseTypeList: StateFlow<List<HouseType>> = _houseTypeList

    private val _designerList = MutableStateFlow<List<Pair<String, String>>>(mutableListOf("全部" to ""))
    val designerList: StateFlow<List<Pair<String, String>>> = _designerList


    /**
     * 社区地区
     */
    private val _designerList2 = MutableStateFlow<List<Pair<String, String>>>(mutableListOf("全部" to ""))
    val regionList: StateFlow<List<Pair<String, String>>> = _designerList2


    val numbers = mutableListOf(
        "1391111111",
        "13814526892",
        "13714526893",
        "13614526894",
    )
    var names = mutableMapOf(
        "1391111111" to "王小二1",
        "13814526892" to "王小二2",
        "13714526893" to "王小二3",
        "13614526894" to "王小二4",
    )

    fun loadData(
    ) {
        viewModelScope.launch {
            loading.value = true
            _questionList.value = emptyList()
            val result = RetrofitService.instance.getHouseLayouts(
                userId = Robot.userId,
                companyId = Robot.companyId,
                accessToken = Robot.accessToken,
                request = FetchDataRequest9(
                    condition = Condition2(
                        name = name.value,
                        houseType = selectedHouseType.value,
                                createUserIds = selectedDesigner.value
                    ).also {
//                        Log.e(TAG, "RetrofitService getHouseLayouts:   Condition2:$it")
                    })
            )
            Log.e(TAG, "result:$result")
            if (result.code==200) {
                Log.e(TAG, "code:200")
                val data = result.data.also {
                    it.list.forEach {
//                        Log.e(TAG, "renderCountrenderCount:"+it.renderCount)
//                        Log.e(TAG, "thumbnail:"+
//                                it.thumbnail="https://ysgkj-oss.oss-cn-hangzhou.aliyuncs.com/picture/other/1693029281758.png"
                    }
                    Log.e(TAG, "size:" +  it.list.size)
                }
                //和杨总沟通 确认使用这个
                val array =data.list.filter { it.pictureUrl!=null }
//                Log.e(TAG, "renderCountrenderCount:array size:"+array.size)
                val itemList = mutableListOf<Item8>()
                array.forEach { item->
                    val id = item.id
                    val name = item.name
                    val thumbnail = item.pictureUrl
                    val roomNum = item.roomNum
                    val hallNum = item.hallNum
                    val washroomNum = item.washroomNum
                    val innerArea = item.innerArea
                    val price = item.price
                    var houseType2 = ""
                    item.houseType?.let {
                        if(it.isNotEmpty()) {
                            houseType2 = parseHouseType(it)
                        }
                    }

                        itemList.add(
                            Item8(
                                id = id,
                                name = name,
                                price = "$price 元",
                                thumbnail = thumbnail,
                                houseType = houseType2,
                                roomNum = roomNum,
                                hallNum = hallNum,
                                washroomNum = washroomNum,
                                innerArea   = String.format("%.2f", innerArea).toDouble(),
                                renderCount =  item.renderCount
                            )
                        )
                }
// 一次性更新 _questionList
                Log.e(TAG, "开始更新界面:"+itemList.size)
                _questionList.value = itemList
            }








            getCustomers()








            loading.value = false
        }
    }

    private suspend fun  getCustomers(){
         val res = RetrofitService.instance.getCustomers(
             accessToken = Robot.accessToken,
             userId = Robot.userId,
             companyId = Robot.companyId,
             request = FetchDataRequest9(
                 condition = Condition3(
                 )
             )
         )
         Log.e(TAG, "客户列表:$res")
         if (res.code == 200) {
             names.clear()
             res.data.list.forEach {
                 names.put(it.customerPhone,it.customerName)
             }

             numbers.clear()
             numbers.addAll( res.data.list.map { it.customerPhone })
         }
     }


    fun loadDataByPhone(
    ) {
        viewModelScope.launch {
            loading.value = true
            _questionList.value = emptyList()
            val result = RetrofitService.instance.getHouseLayouts(
                userId = Robot.userId,
                companyId = Robot.companyId,
                accessToken = Robot.accessToken,
                request = FetchDataRequest9(
                    condition = Condition2(
                        name = name.value,
                        houseType = selectedHouseType.value,
                        createUserIds = selectedDesigner.value
                    ).also {
//                        Log.e(TAG, "RetrofitService getHouseLayouts:   Condition2:$it")
                    })
            )
            Log.e(TAG, "result:$result")
            if (result.code==200) {
                Log.e(TAG, "code:200")
                val data = result.data.also {
                    it.list.forEach {
//                        Log.e(TAG, "renderCountrenderCount:"+it.renderCount)
//                        Log.e(TAG, "thumbnail:"+
//                                it.thumbnail="https://ysgkj-oss.oss-cn-hangzhou.aliyuncs.com/picture/other/1693029281758.png"
                    }
                    Log.e(TAG, "size:" +  it.list.size)
                }
                //和杨总沟通 确认使用这个
                val array =data.list.filter { it.pictureUrl!=null }
//                Log.e(TAG, "renderCountrenderCount:array size:"+array.size)
                val itemList = mutableListOf<Item8>()
                array.forEach { item->
                    val id = item.id
                    val name = item.name
                    val thumbnail = item.pictureUrl
                    val roomNum = item.roomNum
                    val hallNum = item.hallNum
                    val washroomNum = item.washroomNum
                    val innerArea = item.innerArea
                    val price = item.price
                    var houseType2 = ""
                    item.houseType?.let {
                        if(it.isNotEmpty()) {
                            houseType2 = parseHouseType(it)
                        }
                    }

                    itemList.add(
                        Item8(
                            id = id,
                            name = name,
                            price = "$price 元",
                            thumbnail = thumbnail,
                            houseType = houseType2,
                            roomNum = roomNum,
                            hallNum = hallNum,
                            washroomNum = washroomNum,
                            innerArea   = String.format("%.2f", innerArea).toDouble(),
                            renderCount =  item.renderCount
                        )
                    )
                }
// 一次性更新 _questionList
                Log.e(TAG, "开始更新界面:"+itemList.size)
                _questionList.value = itemList
            }
            loading.value = false
        }
    }








    private fun parseHouseType(houseType: String): String {
        // 正则表达式匹配 X房Y厅
        val regex = """(\d+)R(\d+)H""".toRegex()

        // 使用正则表达式匹配
        val matchResult = regex.find(houseType)

        // 如果匹配成功，提取 X 和 Y
        return if (matchResult != null) {
            val (rooms, halls) = matchResult.destructured
            "${rooms}房${halls}厅"
        } else {
            "格式不正确"
        }
    }

    init {
        viewModelScope.launch {
            val s = RetrofitService.instance.getSysDicByType(
                accessToken = Robot.accessToken,
                type = "HOUSE_TYPE"
            )
            _houseTypeList.value += s.data
            Log.e(TAG, "房型:$s")
            RetrofitService.instance.getDesigners(
                accessToken = Robot.accessToken,
                companyId = Robot.companyId
            ).also {
                Log.e(TAG, "搜索公司下的户型图的创建者:${it}")
                it.data.list.map { item ->
                    item.nickname to item.id
                }.also {
                    _designerList.value += it
                }
            }
        }
    }
}

